package com.demo;

import com.demo.advice.MyBeforeAdvice;
import com.demo.service.IUserService;
import com.demo.service.impl.UserServiceImpl;
import org.aopalliance.aop.Advice;
import org.springframework.aop.Pointcut;
import org.springframework.aop.PointcutAdvisor;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.StaticMethodMatcherPointcut;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.lang.reflect.Method;

/**
 * @author shenguangyang
 */

public class AopExample {
    public static void main(String[] args) {
//        example01();
        example02();
    }

    public static void example02() {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
        IUserService userService = applicationContext.getBean(IUserService.class);
        userService.test01();
    }

    public static void example01() {
        IUserService userService = new UserServiceImpl();
        ProxyFactory factory = new ProxyFactory();
        factory.setTarget(userService);
//        factory.addAdvice(new MyAroundAdvice());
//        factory.addAdvice(new MyBeforeAdvice());
        factory.addAdvisor(new PointcutAdvisor() {

            @Override
            public Pointcut getPointcut() {
                return new StaticMethodMatcherPointcut() {
                    @Override
                    public boolean matches(Method method, Class<?> targetClass) {
                        return method.getName().equals("test01");
                    }
                };
            }

            @Override
            public Advice getAdvice() {
                return new MyBeforeAdvice();
            }

            @Override
            public boolean isPerInstance() {
                return false;
            }
        });
        IUserService proxy = (IUserService) factory.getProxy();
        proxy.test01();
        proxy.test02();
    }
}
